package com.project.yuepai.controller.user;


import com.project.yuepai.dao.UserBaseMapper;
import com.project.yuepai.dto.MessageBean;
import com.project.yuepai.dto.UserBaseDto;
import com.project.yuepai.model.User;
import com.project.yuepai.service.SendEmailService;
import com.project.yuepai.service.UserBaseService;
import com.project.yuepai.util.MessageUtil;
import com.project.yuepai.util.QqMsgUtil;
import com.project.yuepai.util.RandomUtil;
import com.project.yuepai.util.RedisTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@RestController
@RequestMapping("/user")
@Validated
public class UserBaseController {

    @Autowired
    private UserBaseService userBaseService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private SendEmailService sendEmailService;

    @Resource
    private UserBaseMapper userBaseMapper;

    //账号+密码登录
    @RequestMapping(value = "/login.action",method = RequestMethod.POST)
    public MessageBean login(String userNumA, String userPwd, HttpSession session){
        User user = new User();
        user.setPhone(userNumA);
        user.setLoginPwd(userPwd);

        UserBaseDto userBaseDto = userBaseService.checkuser(user);
        if(userBaseDto==null)
            return MessageUtil.failure("登录失败！");
        session.setAttribute("user",userBaseDto);
        return MessageUtil.success("登录成功！",userBaseDto);
    }

    //验证码登录
    @RequestMapping(value = "/login.action2",method = RequestMethod.POST)
    public MessageBean loginB(String userVfc, String userNumB, HttpSession session){
        String redisCode = (String) redisTemplateUtil.get(userNumB);
        System.out.println(redisCode);
        if(!userVfc.equals(redisCode)){
            System.out.println("验证码错误！");
            return MessageUtil.failure("验证码错误！");
        }
        User user = new User();
        user.setPhone(userVfc);
        UserBaseDto userBaseDto = userBaseService.checkuser(user);
        session.setAttribute("user",userBaseDto);
        return MessageUtil.success("登录成功！",userBaseDto);
    }

    /**
     * 根据手机号获取验证码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/getPhoneCode.action",method = RequestMethod.POST)
    public MessageBean getCode(@NotBlank(message = "手机号不能为空")@RequestParam("phone") @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号码格式错误") String phone,
                               String templateId )   {
        System.out.println("进来了");
        System.out.println("手机号为"+phone+"获取验证码\ntempleteID:"+templateId);

//        User u=userBaseMapper.findRjuserByUserPhone(phone);
//        System.out.println(u.getPhone());
//        if(u==null){
//            return  MessageUtil.failure("用户不存在！");
//        }

        try {
            String code = RandomUtil.getRandomNum();
            //调用腾讯云短信api,如果发送成功，设置短信5分钟内有效
            if ("success".equals(QqMsgUtil.sendMsg2User(phone, code,Integer.parseInt(templateId))))
                redisTemplateUtil.set(phone,code,5*60);
        } catch (Exception e) {
            e.printStackTrace();
            return MessageUtil.failureBack();
        }
        return MessageUtil.success();
    }

    @RequestMapping(value = "/getEmailCode.action",method = RequestMethod.POST)
    public MessageBean getEmailCode(@NotNull(message = "邮箱不能为空") String email,
                                    @NotNull(message = "标题不能为空") String subject){
        System.out.println("进来了！\n邮箱为"+email+"获取验证码");
        User user = new User();
        user.setEmail(email);
        User u=userBaseMapper.findRjuserByUserEmail(user.getEmail());
        if(u==null){
            return  MessageUtil.failure("用户不存在!");
        }
        String code = RandomUtil.getRandomNum();//获取随机验证码
        if(sendEmailService.sendEmail(email,subject,code)){
            redisTemplateUtil.set(email,code,5*60);
            System.out.println(code);
        }
        return MessageUtil.success();
    }

    @RequestMapping(value = "/register.action",method = RequestMethod.POST)
    public MessageBean register(@NotNull(message = "用户名不能为空") String username,
                                @NotBlank(message = "手机号不能为空") @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号码格式错误") String phone,
                                @NotBlank(message = "验证码不能为空") String code,
                                @NotNull(message = "密码不能为空") String pwd){
        System.out.println("进来了\nusername:"+username+" "+phone+" "+pwd);
        if(userBaseService.judgeUserName(username))
            return MessageUtil.failure("用户名已存在！");
        if(userBaseService.searchUserByPhone(phone)!=null)
            return MessageUtil.failure("手机号已被注册-_-");
        String redisCode = (String) redisTemplateUtil.get(phone);
        if (!code.equals(redisCode)){
            System.out.println("code:"+code+"\nredisCode:"+redisCode);
            return MessageUtil.failure("验证码错误");
        }
        if(userBaseService.createUser(username,phone,pwd))
            return MessageUtil.success("注册成功*_*");
        return MessageUtil.failure("-_- 注册失败 -_- 怎么回事啊 -_-");
    }

    @RequestMapping(value = "/resetPwd.action",method = RequestMethod.POST)
    public MessageBean resetPwd(@NotNull(message = "手机号/邮箱不能为空") String num,
                                @NotNull(message = "验证码不能为空") String code,
                                @NotNull(message = "新密码不能为空") String newPwd,
                                @NotNull(message = "重置类型不能为空") String resetType) {
        String redisCode = (String) redisTemplateUtil.get(num);
        if(!code.equals(redisCode)){
            return MessageUtil.failure("请输入正确的验证码-_-");
        }
        if("手机号".equals(resetType)){
            if(userBaseService.searchUserByPhone(num)==null)
                return MessageUtil.failure("手机号不存在！");
            if(!userBaseService.updatePwdByPhone(num,newPwd))
                return MessageUtil.failure("重置密码失败-_-");
        } else {
            if(userBaseService.searchUserByEmail(num)==null)
                return MessageUtil.failure("邮箱不存在！");
            if(!userBaseService.updatePwdByEmail(num,newPwd))
                return MessageUtil.failure("重置密码失败-_-");
        }
        return MessageUtil.success("重置密码成功*_*");
    }

    //判断用户名是否在数据库中已存在
    @RequestMapping(value = "/judgeUserName.action",method = RequestMethod.GET)
    public MessageBean judgeUserName(String username){
        System.out.println("username:"+username);
        if(userBaseService.judgeUserName(username))
            return MessageUtil.failure("用户名已存在！");
        return MessageUtil.success("用户名唯一");
    }
}
